package com.tuling.netty;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NioClassDemo {
    public static void main(String[] args)  throws Exception{
        SelectableChannel selectableChannel = ServerSocketChannel.open()
                .bind(new InetSocketAddress(9000))
                .configureBlocking(false);
        //多路复用器
        Selector selector = Selector.open();
        selectableChannel.register(selector, SelectionKey.OP_ACCEPT);


        while(true){
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = selectionKeys.iterator().next();
                if(key.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel)key.channel();
                    channel.configureBlocking(false);
                    SocketChannel socketChannel = channel.accept();
                    socketChannel.register(selector,SelectionKey.OP_READ);
                    System.out.println("客户端连接成功");
                } else if (key.isReadable()) {
                    SocketChannel channel =(SocketChannel) key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                    int read = channel.read(byteBuffer);
                    if(read == -1){
                        System.out.println("客户端断开连接");
                        channel.close();
                    }else{
                        System.out.println(new String(byteBuffer.array()));
                    }

                }
                iterator.remove();
            }

        }

    }
}
